//
//  PaymentView.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import SwiftUI
import Foundation

struct PaymentView: View {
    let subtotal: Double
    let tax: Double
    let discount: Double
    let total: Double
    let appliedCoupon: Coupon?
    let pointsUsed: Int
    let reservationTime: Date? // 预订时间
    let reservationInfo: ReservationConfig.ReservationInfo? // 预订信息
    
    @EnvironmentObject var dataManager: DataManager
    @Environment(\.presentationMode) var presentationMode
    @State private var selectedPaymentMethod: PaymentMethod = .creditCard
    
    @State private var isProcessingPayment = false
    @State private var showingOrderConfirmation = false
    @State private var createdOrder: Order?
    
    // 检查是否只有Cash Voucher
    private var hasOnlyCashVoucher: Bool {
        let hasCashVoucher = dataManager.cartItems.contains { $0.menuItem.name == AppConfig.Cart.voucherPackageName }
        return hasCashVoucher && dataManager.cartItems.allSatisfy { $0.menuItem.name == AppConfig.Cart.voucherPackageName }
    }
    
    // 计算总折扣（与CartView保持一致）
    private var calculatedTotalDiscount: Double {
        guard !hasOnlyCashVoucher else { return 0 }
        
        var totalDiscount = appliedCoupon?.calculateDiscount(for: subtotal) ?? 0
        
        // 积分抵扣计算（与CartView保持一致）
        if let user = dataManager.currentUser {
            let membershipLevel = user.membershipLevel
            if pointsUsed >= membershipLevel.minimumPointsForDiscount {
                let discountGroups = pointsUsed / membershipLevel.pointsPerDiscount
                totalDiscount += Double(discountGroups) * 5.0
            }
        }
        
        return totalDiscount
    }
    
    var body: some View {
        NavigationView {
            ScrollView(.vertical, showsIndicators: true) {
                VStack(spacing: 25) {
                    // 订单摘要
                    orderSummary
                    
                    // 用餐信息 - 只有Cash Voucher时显示N/A
                    if hasOnlyCashVoucher {
                        cashVoucherDiningInfo
                    } else {
                        diningInfo
                    }
                    
                    // 支付方式选择
                    paymentMethodSelection
                    
                    // 价格明细
                    priceBreakdown
                }
                .padding(.horizontal, 20)
                .padding(.bottom, 140)
            }
            .background(
                LinearGradient(
                    colors: [
                        Color(red: 0.12, green: 0.12, blue: 0.12),
                        Color(red: 0.18, green: 0.16, blue: 0.15)
                    ],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .ignoresSafeArea()
            )
            .navigationTitle(dataManager.currentLanguage == "zh" ? "支付" : "Payment")
            .navigationBarTitleDisplayMode(.inline)
            .navigationBarBackButtonHidden(true)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button(dataManager.currentLanguage == "zh" ? "取消" : "Cancel") {
                        presentationMode.wrappedValue.dismiss()
                    }
                }
            }
            .overlay(
                // 支付按钮
                VStack {
                    Spacer()
                    Button(action: processPayment) {
                        HStack {
                            if isProcessingPayment {
                                ProgressView()
                                    .progressViewStyle(CircularProgressViewStyle(tint: Color(red: 0.12, green: 0.12, blue: 0.12)))
                                    .scaleEffect(0.8)
                            }
                            
                            Text(isProcessingPayment ? 
                                 (dataManager.currentLanguage == "zh" ? "处理中..." : "Processing...") :
                                 (dataManager.currentLanguage == "zh" ? "确认支付 S$\(total, specifier: "%.2f")" : "Confirm Payment S$\(total, specifier: "%.2f")"))
                                .font(.headline)
                                .fontWeight(.semibold)
                        }
                        .foregroundColor(Color(red: 0.12, green: 0.12, blue: 0.12))
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 15)
                        .background(
                            RoundedRectangle(cornerRadius: 12)
                                .fill(Color(red: 1.0, green: 0.6, blue: 0.2))
                        )
                    }
                    .disabled(isProcessingPayment)
                    .padding(.horizontal, 20)
                    .padding(.bottom, 34) // Safe area bottom padding
                    .background(
                        Rectangle()
                            .fill(Color(red: 0.12, green: 0.12, blue: 0.12))
                            .ignoresSafeArea(edges: .bottom)
                    )
                },
                alignment: .bottom
            )
        }
        .sheet(isPresented: $showingOrderConfirmation) {
            if let order = createdOrder {
                OrderConfirmationView(order: order)
                    .environmentObject(dataManager)
            }
        }

    }
    
    // MARK: - 订单摘要
    private var orderSummary: some View {
        VStack(alignment: .leading, spacing: 15) {
            Text(dataManager.currentLanguage == "zh" ? "订单摘要" : "Order Summary")
                .font(.title2)
                .fontWeight(.semibold)
                .foregroundColor(.white)
            
            VStack(spacing: 10) {
                ForEach(dataManager.cartItems) { cartItem in
                    HStack {
                        Text("\(cartItem.quantity)x")
                            .font(.subheadline)
                            .foregroundColor(.gray)
                            .frame(width: 30, alignment: .leading)
                        
                        VStack(alignment: .leading, spacing: 2) {
                            Text(dataManager.currentLanguage == "zh" ? cartItem.menuItem.name : cartItem.menuItem.englishName)
                                .font(.subheadline)
                                .foregroundColor(.white)
                            
                            if let meatType = cartItem.selectedMeatType {
                                Text(dataManager.currentLanguage == "zh" ? meatType.rawValue : meatType.englishName)
                                    .font(.caption)
                                    .foregroundColor(.gray)
                            }
                            
                            if !cartItem.specialInstructions.isEmpty {
                                Text(cartItem.specialInstructions)
                                    .font(.caption)
                                    .foregroundColor(.gray)
                                    .lineLimit(2)
                            }
                        }
                        
                        Spacer()
                        
                        Text("S$\(cartItem.totalPrice, specifier: "%.2f")")
                            .font(.subheadline)
                            .fontWeight(.medium)
                            .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                    }
                }
            }
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 15)
                .fill(
                    LinearGradient(
                        gradient: Gradient(colors: [
                            Color(red: 0.15, green: 0.15, blue: 0.15),
                            Color(red: 0.1, green: 0.1, blue: 0.1),
                            Color(red: 0.05, green: 0.05, blue: 0.05)
                        ]),
                        startPoint: .top,
                        endPoint: .bottom
                    )
                )
        )
    }
    
    // Cash Voucher专用的用餐信息显示
    private var cashVoucherDiningInfo: some View {
        VStack(alignment: .leading, spacing: 15) {
            Text(dataManager.currentLanguage == "zh" ? "用餐信息" : "Dining Information")
                .font(.title2)
                .fontWeight(.semibold)
                .foregroundColor(.white)
            
            VStack(spacing: 12) {
                HStack {
                    Text(dataManager.currentLanguage == "zh" ? "用餐方式" : "Dining Type")
                        .foregroundColor(.gray)
                        .font(.subheadline)
                    Spacer()
                    Text("N/A")
                        .foregroundColor(.white)
                        .font(.subheadline)
                }
                
                HStack {
                    Text(dataManager.currentLanguage == "zh" ? "积分获得" : "Points Earned")
                        .foregroundColor(.gray)
                        .font(.subheadline)
                    Spacer()
                    Text("0")
                        .foregroundColor(.white)
                        .font(.subheadline)
                }
                
                if let user = dataManager.currentUser {
                    HStack {
                        Text(dataManager.currentLanguage == "zh" ? "手机号" : "Phone Number")
                            .foregroundColor(.gray)
                        Spacer()
                        Text("+65\(user.phoneNumber)")
                            .foregroundColor(.white)
                    }
                }
            }
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 15)
                .fill(
                    LinearGradient(
                        gradient: Gradient(colors: [
                            Color(red: 0.15, green: 0.15, blue: 0.15),
                            Color(red: 0.1, green: 0.1, blue: 0.1),
                            Color(red: 0.05, green: 0.05, blue: 0.05)
                        ]),
                        startPoint: .top,
                        endPoint: .bottom
                    )
                )
        )
    }
    
    // MARK: - 用餐信息
    private var diningInfo: some View {
        VStack(alignment: .leading, spacing: 15) {
            Text(dataManager.currentLanguage == "zh" ? "用餐信息" : "Dining Information")
                .font(.title2)
                .fontWeight(.semibold)
                .foregroundColor(.white)
            
            VStack(spacing: 12) {
                // 显示预订信息摘要或立即用餐信息
                if let reservationInfo = reservationInfo {
                    // 预订类型
                    HStack {
                        Text(dataManager.currentLanguage == "zh" ? "预订类型" : "Reservation Type")
                            .foregroundColor(.gray)
                            .font(.subheadline)
                        Spacer()
                        Text(Order.displayOrderType(diningType: dataManager.selectedDiningType, isReservation: true, language: dataManager.currentLanguage))
                            .foregroundColor(.white)
                            .font(.subheadline)
                    }
                    
                    // 用餐人数
                    HStack {
                        Text(dataManager.currentLanguage == "zh" ? "用餐人数" : "Party Size")
                            .foregroundColor(.gray)
                            .font(.subheadline)
                        Spacer()
                        Text("\(reservationInfo.partySize) \(dataManager.currentLanguage == "zh" ? "人" : "people")")
                            .foregroundColor(.white)
                            .font(.subheadline)
                    }
                    
                    // 座位偏好
                    HStack {
                        Text(dataManager.currentLanguage == "zh" ? "座位偏好" : "Seating Preference")
                            .foregroundColor(.gray)
                            .font(.subheadline)
                        Spacer()
                        Text(dataManager.currentLanguage == "zh" ? reservationInfo.seatingType.chineseName : reservationInfo.seatingType.englishName)
                            .foregroundColor(.white)
                            .font(.subheadline)
                    }
                    
                    // 预订时间
                    HStack {
                        Text(dataManager.currentLanguage == "zh" ? "预订时间" : "Reservation Time")
                            .foregroundColor(.gray)
                            .font(.subheadline)
                        Spacer()
                        VStack(alignment: .trailing, spacing: 2) {
                            Text(formatDate(reservationInfo.reservationTime))
                                .foregroundColor(.white)
                                .font(.subheadline)
                            Text(formatTime(reservationInfo.reservationTime))
                                .foregroundColor(.white)
                                .font(.subheadline)
                        }
                    }
                    
                    // 特殊要求（如果有）
                    if let specialRequests = reservationInfo.specialRequests, !specialRequests.isEmpty {
                        VStack(alignment: .leading, spacing: 4) {
                            Text(dataManager.currentLanguage == "zh" ? "特殊要求" : "Special Requests")
                                .foregroundColor(.gray)
                                .font(.subheadline)
                            Text(specialRequests)
                                .foregroundColor(.white)
                                .font(.subheadline)
                                .multilineTextAlignment(.leading)
                        }
                    }
                } else {
                    // 立即用餐信息
                    HStack {
                        Text(dataManager.currentLanguage == "zh" ? "用餐方式" : "Dining Type")
                            .foregroundColor(.gray)
                            .font(.subheadline)
                        Spacer()
                        Text(Order.displayOrderType(diningType: dataManager.selectedDiningType, isReservation: false, language: dataManager.currentLanguage))
                            .foregroundColor(.white)
                            .font(.subheadline)
                    }
                    
                    // 如果是堂食，显示桌号信息
                    if dataManager.selectedDiningType == .dineIn {
                        HStack {
                            Text(dataManager.currentLanguage == "zh" ? "桌号" : "Table Number")
                                .foregroundColor(.gray)
                                .font(.subheadline)
                            Spacer()
                            Text(dataManager.currentTableNumber ?? (dataManager.currentLanguage == "zh" ? "扫码入座" : "Scan to Seat"))
                                .foregroundColor(.white)
                                .font(.subheadline)
                        }
                    }
                }
                
                // 手机号信息
                if let user = dataManager.currentUser {
                    HStack {
                        Text(dataManager.currentLanguage == "zh" ? "手机号" : "Phone Number")
                            .foregroundColor(.gray)
                            .font(.subheadline)
                        Spacer()
                        Text("+65\(user.phoneNumber)")
                            .foregroundColor(.white)
                            .font(.subheadline)
                    }
                }
            }
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 15)
                .fill(
                    LinearGradient(
                        gradient: Gradient(colors: [
                            Color(red: 0.15, green: 0.15, blue: 0.15),
                            Color(red: 0.1, green: 0.1, blue: 0.1),
                            Color(red: 0.05, green: 0.05, blue: 0.05)
                        ]),
                        startPoint: .top,
                        endPoint: .bottom
                    )
                )
        )
    }
    
    // MARK: - 支付方式选择
    private var paymentMethodSelection: some View {
        VStack(alignment: .leading, spacing: 15) {
            Text(dataManager.currentLanguage == "zh" ? "支付方式" : "Payment Method")
                .font(.title2)
                .fontWeight(.semibold)
                .foregroundColor(.white)
            
            VStack(spacing: 10) {
                ForEach(PaymentMethod.allCases, id: \.self) { method in
                    Button(action: {
                        selectedPaymentMethod = method
                    }) {
                        HStack(spacing: 15) {
                            Image(systemName: paymentMethodIcon(for: method))
                                .font(.title2)
                                .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                                .frame(width: 30)
                            
                            Text(dataManager.currentLanguage == "zh" ? method.rawValue : method.englishName)
                                .font(.subheadline)
                                .foregroundColor(.white)
                            
                            Spacer()
                            
                            Image(systemName: selectedPaymentMethod == method ? "checkmark.circle.fill" : "circle")
                                .font(.title3)
                                .foregroundColor(selectedPaymentMethod == method ? Color(red: 1.0, green: 0.6, blue: 0.2) : .gray)
                        }
                        .padding(15)
                        .background(
                            RoundedRectangle(cornerRadius: 10)
                                .fill(Color(red: 0.25, green: 0.22, blue: 0.20))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 10)
                                        .stroke(
                                            selectedPaymentMethod == method ? Color(red: 1.0, green: 0.6, blue: 0.2) : Color.clear,
                                            lineWidth: 2
                                        )
                                )
                        )
                    }
                    .buttonStyle(PlainButtonStyle())
                }
            }
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 15)
                .fill(
                    LinearGradient(
                        gradient: Gradient(colors: [
                            Color(red: 0.15, green: 0.15, blue: 0.15),
                            Color(red: 0.1, green: 0.1, blue: 0.1),
                            Color(red: 0.05, green: 0.05, blue: 0.05)
                        ]),
                        startPoint: .top,
                        endPoint: .bottom
                    )
                )
        )
    }
    
    
    
    // MARK: - 价格明细
    private var priceBreakdown: some View {
        VStack(spacing: 15) {
            Text(dataManager.currentLanguage == "zh" ? "价格明细" : "Price Breakdown")
                .font(.title2)
                .fontWeight(.semibold)
                .foregroundColor(.white)
            
            VStack(spacing: 12) {
                HStack {
                    Text(dataManager.currentLanguage == "zh" ? (hasOnlyCashVoucher ? "小计" : "税前小计") : (hasOnlyCashVoucher ? "Subtotal" : "Subtotal before GST"))
                        .foregroundColor(.gray)
                    Spacer()
                    Text("S$\(subtotal, specifier: "%.2f")")
                        .foregroundColor(.white)
                }
                
                // 只有在非Cash Voucher情况下才显示折扣
                if !hasOnlyCashVoucher && calculatedTotalDiscount > 0 {
                    HStack {
                        Text(dataManager.currentLanguage == "zh" ? "折扣" : "Discount")
                            .foregroundColor(.gray)
                        Spacer()
                        Text("-S$\(calculatedTotalDiscount, specifier: "%.2f")")
                            .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                    }
                }
                
                HStack {
                    Text("GST (9%)")
                        .foregroundColor(.gray)
                    Spacer()
                    Text("S$\(tax, specifier: "%.2f")")
                        .foregroundColor(.white)
                }
                
                Divider()
                    .background(Color.gray)
                
                HStack {
                    Text(dataManager.currentLanguage == "zh" ? "总计" : "Total")
                        .font(.headline)
                        .fontWeight(.semibold)
                        .foregroundColor(.white)
                    Spacer()
                    Text("S$\(total, specifier: "%.2f")")
                        .font(.title2)
                        .fontWeight(.bold)
                        .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                }
            }
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 15)
                .fill(Color(red: 0.2, green: 0.2, blue: 0.2))
        )
    }
    
    // MARK: - 辅助方法
    private func paymentMethodIcon(for method: PaymentMethod) -> String {
        switch method {
        case .creditCard:
            return "creditcard.fill"
        case .payNow:
            return "qrcode"
        case .applePay:
            return "applelogo"
        case .googlePay:
            return "g.circle.fill"
        }
    }
    
    private func formatDate(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = dataManager.currentLanguage == "zh" ? "MM月dd日" : "MMM dd"
        return formatter.string(from: date)
    }
    
    private func formatTime(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm"
        return formatter.string(from: date)
    }
    
    private func processPayment() {
        isProcessingPayment = true
        
        // 模拟支付处理
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: DispatchWorkItem {
            // 如果是预订订单，进行最终座位可用性检查
            if let reservationInfo = reservationInfo {
                let availableSeats = ReservationConfig.SeatAvailability.getAvailableSeats(
                    for: reservationInfo.seatingType,
                    at: reservationInfo.reservationTime,
                    time: reservationInfo.reservationTime,
                    partySize: reservationInfo.partySize,
                    dataManager: dataManager
                )
                
                // 检查是否有足够的座位
                if availableSeats < reservationInfo.partySize {
                    // 座位不足，取消支付处理
                    isProcessingPayment = false
                    // 这里可以显示错误提示，但按要求不改变UI
                    return
                }
            }
            
            // 创建订单（现金券套餐的处理逻辑已在createOrder中完成）
            let order = dataManager.createOrderWithPersistence(
                paymentMethod: selectedPaymentMethod,
                specialInstructions: nil,
                appliedCoupon: appliedCoupon,
                pointsUsed: pointsUsed,
                reservationTime: reservationTime,
                reservationInfo: reservationInfo
            )
            
            // 如果使用了礼券，记录礼券使用状态
            if let coupon = appliedCoupon {
                dataManager.recordCouponUsage(coupon)
            }
            
            // 注意：现金券套餐的处理（包括现金券发放）已在createOrder方法中完成
            // 不需要在这里重复调用purchaseValueVoucherPackage()
            
            createdOrder = order
            isProcessingPayment = false
            presentationMode.wrappedValue.dismiss()
            
            // 触发导航到Orders/Current
            dataManager.shouldNavigateToOrdersCurrent = true
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: DispatchWorkItem {
                showingOrderConfirmation = true
            })
        })
    }
    

}

#Preview {
    PaymentView(
        subtotal: 25.80,
        tax: 1.81,
        discount: 2.58,
        total: 25.03,
        appliedCoupon: nil,
        pointsUsed: 0,
        reservationTime: nil,
        reservationInfo: nil
    )
    .environmentObject(DataManager.shared)
}